package cn.e3mall.cart.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import cn.e3mall.cart.service.CartService;
import cn.e3mall.common.jedis.JedisClient;
import cn.e3mall.common.util.E3Result;
import cn.e3mall.common.util.JsonUtils;
import cn.e3mall.mapper.TbItemMapper;
import cn.e3mall.pojo.TbItem;

/*
 * 登陆状态 ， 购物车处理服务
 */
@Service
public class CartServiceImpl implements CartService {

	@Autowired
	private JedisClient jedisClient;
	@Value("${REDIS_CART_PRE}")
	private String REDIS_CART_PRE;
	@Autowired
	private TbItemMapper itemMapper;
	
	
	@Override
	public E3Result addCart(long userId, long itemId,int num) {
		
		//判断商品是否存在
		Boolean hexists = jedisClient.hexists(REDIS_CART_PRE+":"+userId, itemId+"");
		if (hexists) {
			String json = jedisClient.hget(REDIS_CART_PRE+":"+userId, itemId+"");	
			TbItem item = JsonUtils.jsonToPojo(json, TbItem.class);
			item.setNum(item.getNum()+num);
			jedisClient.hset(REDIS_CART_PRE+":"+userId, itemId+"", JsonUtils.objectToJson(item));
			return E3Result.ok();
		}
		//如果商品不存在
		TbItem item = itemMapper.selectByPrimaryKey(itemId);
		item.setNum(num);
		if(StringUtils.isNotBlank(item.getImage())){
			item.setImage(item.getImage().split(",")[0]);
		}
		//商品添加redis
		jedisClient.hset(REDIS_CART_PRE+":"+userId, itemId+"", JsonUtils.objectToJson(item));
		
		return E3Result.ok();
	}


	@Override
	public E3Result mergeCart(long userId, List<TbItem> list) {
		// 遍历商品列表，添加到购物车
		//判断购物车中是否有此商品
		//如果有，数量相加
		//如果没有添加新商品
		for (TbItem tbItem : list) {
			addCart(userId, tbItem.getId(), tbItem.getNum());
		}
		
		return E3Result.ok();
	}


	@Override
	public List<TbItem> getCartList(long userId) {
		// 根据用户id查询cookie中购物车列表
		List<String> jsonList = jedisClient.hvals(REDIS_CART_PRE+":"+userId);
		List<TbItem> itemList = new ArrayList<TbItem>();
		for (String str :jsonList) {
			TbItem item = JsonUtils.jsonToPojo(str, TbItem.class);
			//添加到列表
			itemList.add(item);
		}
		return itemList;
		
	}


	@Override
	public E3Result updataCartNum(long userId, long itemId, int num) {
		//从redis取商品信息
		String json = jedisClient.hget(REDIS_CART_PRE+":"+userId, itemId+"");
		TbItem item = JsonUtils.jsonToPojo(json, TbItem.class);
		item.setNum(num);
		jedisClient.hset(REDIS_CART_PRE+":"+userId, itemId+"",
				JsonUtils.objectToJson(item));
		return E3Result.ok();
	}


	@Override
	public E3Result deleteCartItem(long userId, long itemId) {

		jedisClient.hdel(REDIS_CART_PRE+":"+userId, itemId+"");
		return E3Result.ok();
	}

	//清空用户购物车
	@Override
	public E3Result clearCartItem(long userId) {
		jedisClient.del(REDIS_CART_PRE+":"+userId);
		
		return E3Result.ok();
	}

}
